/**
 * utils/sort-qb
 *
 * 按规则处理 query build
 */

const setSort = function(qb, name, val) {
    qb.orderBy(name, val || 'asc');
};

const defaultAllowdSorts = {
    'id-asc': ['id', 'asc'],
    'id-desc': ['id', 'desc'],

    'priority-asc': [
        'priority', 'asc',
        'id', 'asc'
    ],
    'default': [
        'priority', 'desc',
        'id', 'desc'
    ]
};

module.exports.defaultAllowdSorts = defaultAllowdSorts;

module.exports = function(allowdSorts = defaultAllowdSorts) {
    return function(qb, type) {
        let sortCfg = allowdSorts[type] || allowdSorts.default;

        if(!qb || !sortCfg || !sortCfg.length) {
            return null;
        }

        if(sortCfg.length <= 2) {
            setSort(qb, sortCfg[0], sortCfg[1]);
        }
        else {
            for(let i = 0, len = sortCfg.length; i < len; i += 2) {
                setSort(qb, sortCfg[i], sortCfg[i + 1]);
            }
        }

        return sortCfg;
    };
};
